# -*- coding:utf-8 -*-
"""
Create by Jim on2019/01/09
"""

from flask import jsonify, session, request
from flask_login import login_user, logout_user

from info import redis_store, login_manager
from info.models import User
from info.utils.response_code import RET, error_map
from . import auth
from info.utils.resp_model import RespViewModel


@login_manager.user_loader
def load_user(userid):
    return User.get(userid)

@auth.route('/')
def index():
    return 'index'


@auth.route('/imagecode/', methods=['GET'])
def imagecode():
    return jsonify()


@auth.route('/smscode/', methods=['POST'])
def smscode():
    return jsonify()


# 用户登录 退出登陆 获取状态
@auth.route('/session/', methods=['POST', 'GET', 'DELETE'])
def sess():
    """
    POST:用于登录
    GET：用于获取用户状态
    DELETE:用于退出登录
    :return:
    """
    if request.method == 'DELETE':
        redis_store.delete("username", None)
        redis_store.delete("password", None)
        logout_user()
        return jsonify(RespViewModel(RET.OK, error_map.get(RET.OK)))
    if request.method == 'GET':
        username = session.get('username', None)
        if not username:
            return jsonify(RespViewModel(RET.NODATA, error_map.get(RET.NODATA)))
        user = User.query.filter_by(name=username).first()
        if user:
            data = {
                "name": username,
                "user_id": user.id
            }
        return jsonify(RespViewModel(RET.OK, error_map.get(RET.OK, data)))
    mobile = request.form.get('mobile', None)
    password = request.form.get('password', None)
    if all([mobile, password]):
        jsonify(RespViewModel(RET.NODATA, error_map.get(RET.NODATA)))
    user = User.query.filter_by(mobile=mobile).first()
    if not user.check_passowrd(password):
        return jsonify(RespViewModel(RET.PWDERR, error_map.get(RET.PWDERR)))
    login_user(user)
    return jsonify(RespViewModel(RET.OK, error_map.get(RET.OK),{'name':'jim'}).resp_data())

